extends CharacterBody3D

signal bat_placed
signal bat_took_away

# How fast the player moves in meters per second
@export var speed = 14
# The downward acceleration while in the air, in meters per second squared.
@export var fall_acceleration = 75
# Vertical impulse applied to the character upon jumping in meters per second.
@export var jump_impulse = 20
# Vertical impulse applied to the character upon bouncing over a mob
# in meters per second.
@export var bounce_impulse = 16

var target_velocity = Vector3.ZERO
var battery = null
var bat_soc = 0
var veh_moving = false
var bat_pos = Vector3.ZERO

func _ready():
	$Cabinet.set_auto_charge(false)

func _physics_process(delta):
	# We create a local variable to store the input direction
	var direction = Vector3.ZERO

	# We check for each move input and update the direction accordingly
	if Input.is_action_pressed("move_right"):
		direction.x = direction.x + 1
	if Input.is_action_pressed("move_left"):
		direction.x = direction.x - 1
	if Input.is_action_pressed("move_back"):
		# Notice how we are working with the vector's x and z axes.
		# In 3D, the XZ plane is the ground plane.
		direction.z = direction.z + 1
	if Input.is_action_pressed("move_forward"):
		direction.z = direction.z - 1

	# Ground Velocity
	target_velocity.x = direction.x * speed
	target_velocity.z = direction.z * speed

	# Vertical Velocity
	# if not is_on_floor(): # If in the air, fall towards the floor. Literally gravity
	#	target_velocity.y = target_velocity.y - (fall_acceleration * delta)

	# Jumping.
	#if is_on_floor() and Input.is_action_just_pressed("jump"):
	#	target_velocity.y = jump_impulse
	# Moving the Character
	
	if (battery):
		if (target_velocity.x || target_velocity.y):
			veh_moving = true
		velocity = target_velocity
		move_and_slide()
		bat_pos = battery.position
	#$Pivot.rotation.x = PI / 6 * velocity.y / jump_impulse

func get_cabinet_pos():
	return $Cabinet.position + position

func get_cabinet():
	return $Cabinet
	
func get_battery():
	return battery

func set_battery(bat):
	battery = bat
	bat_pos = bat.position
	bat_soc = bat._get_soc()

func remove_battery_ins():
	remove_child($Battery)

func _on_cabinet_bat_detect(body):
	print("battery on veh detect")
	battery = body
	bat_soc = battery._get_soc()
	print("battery: " + battery.name + ", soc: " + str(bat_soc))
	bat_placed.emit()

func _on_cabinet_bat_away(body):
	bat_soc = 0
	print("battery: " + battery.name + " is took away")
	battery = null
	bat_took_away.emit()

func _on_timer_timeout():
	if (battery && veh_moving):
		veh_moving = false
		if(battery._get_soc() > 0):
			bat_soc = battery._get_soc() - 1
			battery._set_soc(bat_soc)
